package cn.bugstack.gateway.bind;

import net.sf.cglib.proxy.Enhancer;
import org.apache.dubbo.rpc.service.GenericService;

public enum GenericReferenceProxyFactory {
    INSTANCE;
    // 枚举单例，不使用 Concurrenthashmap，
    private GenericService genericService;
    private IGenericReference genericReference;

    GenericReferenceProxyFactory() {
        // 初始化时不需要传入 genericService
    }

    public static GenericReferenceProxyFactory getInstance(GenericService genericService, String methodName) {
        INSTANCE.genericService = genericService;
        INSTANCE.genericReference = INSTANCE.createGenericReference(methodName);
        return INSTANCE;
    }

    public IGenericReference getGenericReference() {
        return genericReference;
    }

    private IGenericReference createGenericReference(String methodName) {
        // 创建回调代理对象
        GenericReferenceProxy genericReferenceProxy = new GenericReferenceProxy(genericService, methodName);

        // interfaceClass    还可以根据泛化调用注册信息创建的接口，建立 http -> rpc 关联
        //enhancer.setInterfaces(new Class[]{IGenericReference.class, interfaceClass});
        
        // 创建cglib代理对象
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(Object.class);
        enhancer.setInterfaces(new Class[]{IGenericReference.class});
        enhancer.setCallback(genericReferenceProxy);

        return (IGenericReference) enhancer.create();
    }
}